package com.tencent.ncnnyolox.net;

import android.util.Log;

import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class LoggingInterceptor implements Interceptor {

   @Override
   public Response intercept(Chain chain) throws IOException {
      Request request = chain.request();

      // 打印请求日志
      Log.d("OkHttp","Request: " + request.method() + " " + request.url());

      long startTime = System.nanoTime();
      Response response;

      try {
         // 继续请求链
         response = chain.proceed(request);
      } catch (Exception e) {
         // 请求异常
         Log.d("OkHttp","Request failed: " + e.getMessage());
         throw e;
      }

      long endTime = System.nanoTime();
      long duration = (endTime - startTime) / 1_000_000; // 毫秒

      // 打印响应日志
      Log.d("OkHttp","Response: " + response.code() + " (" + duration + " ms)");

      // 打印响应体
      ResponseBody responseBody = response.body();
      String responseBodyString = responseBody != null ? responseBody.string() : "";
      Log.d("OkHttp","Response Body: " + responseBodyString);

      // 重建响应体，因为ResponseBody.string()只能读取一次
      Response newResponse = response.newBuilder()
              .body(ResponseBody.create(responseBody != null ? responseBody.contentType() : null, responseBodyString))
              .build();

      return newResponse;
   }
}
